<template>
  <div class="favorites">
    <el-container>
      <el-header>
        <div class="header-content">
          <div class="header-left">
            <el-button type="primary" @click="router.push('/')">
              <el-icon><ArrowLeft /></el-icon>
              返回主页
            </el-button>
          </div>
          <div class="header-right">
            <h2>我的收藏</h2>
          </div>
        </div>
      </el-header>
      <el-main>
        <el-card class="favorites-card">
          <template #header>
            <div class="card-header">
              <span>收藏列表</span>
            </div>
          </template>
          
          <el-table 
            :data="favoritesList" 
            style="width: 100%"
            v-loading="loading"
          >
            <el-table-column label="商品信息" min-width="400">
              <template #default="scope">
                <div class="product-info" @click="toProductDetail(scope.row.productId)">
                  <el-image 
                    :src="scope.row.productImage" 
                    fit="cover"
                    class="product-image"
                  />
                  <div class="product-details">
                    <div class="product-name">{{ scope.row.productName }}</div>
                    <div class="farm-name">{{ scope.row.farmName }}</div>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="price" label="价格" width="120">
              <template #default="scope">
                ¥{{ scope.row.price }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
                  {{ scope.row.status === 1 ? '上架中' : '已下架' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="collectTime" label="收藏时间" width="180">
              <template #default="scope">
                {{ formatDate(scope.row.collectTime) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120">
              <template #default="scope">
                <el-button 
                  type="danger" 
                  size="small" 
                  @click="cancelFavorite(scope.row.productId)"
                >
                  取消收藏
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <div class="empty-placeholder" v-if="favoritesList.length === 0">
            <el-empty description="暂无收藏" />
          </div>
        </el-card>
      </el-main>
    </el-container>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'
import { getFavoritesList, removeFromFavorites } from '@/api/products'

const router = useRouter()
const loading = ref(false)
const favoritesList = ref([])

// 加载收藏列表
const loadFavorites = async () => {
  loading.value = true
  try {
    const response = await getFavoritesList()
    console.log('收藏列表完整响应:', response)
    
    // 直接判断response是否为数组
    if (Array.isArray(response)) {
      favoritesList.value = response
      if (favoritesList.value.length > 0) {
        console.log('成功加载收藏列表，共', favoritesList.value.length, '条记录')
      } else {
        console.log('收藏列表为空')
      }
    } else {
      console.error('获取收藏列表失败:', '响应格式错误')
      ElMessage.error('获取收藏列表失败')
    }
  } catch (error) {
    console.error('获取收藏列表失败:', error)
    ElMessage.error('获取收藏列表失败: ' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

// 取消收藏
const cancelFavorite = async (productId) => {
  try {
    const res = await removeFromFavorites(productId)
    if (res.success === true) {
      ElMessage.success(res.message || '取消收藏成功')
      // 重新加载收藏列表
      loadFavorites()
    } else {
      ElMessage.error(res.message || '取消收藏失败')
    }
  } catch (error) {
    console.error('取消收藏失败:', error)
    ElMessage.error('操作失败，请重试')
  }
}

// 跳转到商品详情
const toProductDetail = (productId) => {
  const favorite = favoritesList.value.find(item => item.productId === productId)
  if (favorite) {
    router.push(`/product/${favorite.farmId}/${productId}`)
  }
}

// 格式化日期
const formatDate = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 组件挂载时加载数据
onMounted(() => {
  loadFavorites()
})
</script>

<style scoped>
.favorites {
  height: 100vh;
  background-color: #f5f7fa;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
}

.favorites-card {
  margin: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.product-info {
  display: flex;
  align-items: center;
  gap: 15px;
  cursor: pointer;
}

.product-info:hover {
  opacity: 0.8;
}

.product-image {
  width: 80px;
  height: 80px;
  border-radius: 4px;
}

.product-details {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.product-name {
  font-size: 14px;
  font-weight: 500;
}

.farm-name {
  font-size: 12px;
  color: #666;
}

.empty-placeholder {
  padding: 40px 0;
}
</style> 